/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * LoanUI.java
 *
 * Created on 2010.11.10., 1:26:24
 */
package workshopdesign.UI;

import java.text.SimpleDateFormat;
import java.util.Collection;
import javax.swing.RowFilter;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableRowSorter;
import org.jdesktop.application.Action;
import workshopdesign.Control.LoanController;
import workshopdesign.Model.Loan;

/**
 *
 * @author Dom
 */
public class LoanUI extends javax.swing.JPanel implements BaseUIController {

    private LoanController loanController = LoanController.getLoanController();
    private SimpleDateFormat sdf = (SimpleDateFormat) SimpleDateFormat.getInstance();
    private LoanDetailUI loanDetailUI;
    private DVDDetailUI dVDDetailUI;
    private PersonDetailUI personDetailUI;
    private DefaultTableModel model;
    private TableRowSorter<DefaultTableModel> sorter;

    /** Creates new form LoanUI */
    public LoanUI() {
        initComponents();

        loanDetailUI = new LoanDetailUI(this, "Details", true);
        dVDDetailUI = new DVDDetailUI(this, "DVD details", false);
        personDetailUI = new PersonDetailUI(this, "Rented by", false);

        // TODO: Loan list UI
        loan_detail_splitter.setTopComponent(loanDetailUI);
        loan_loan_splitter.setTopComponent(personDetailUI);
        loan_loan_splitter.setBottomComponent(dVDDetailUI);

        model = (DefaultTableModel) loan_table.getModel();
        sorter = new TableRowSorter<DefaultTableModel>(model);
        loan_table.setRowSorter(sorter);

        filter_field.getDocument().addDocumentListener(new DocumentListener() {

            @Override
            public void insertUpdate(DocumentEvent e) {
                filter_data();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                filter_data();
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                filter_data();
            }
        });

        DefaultTableColumnModel columnModel = new DefaultTableColumnModel();
        TableColumn id_column = new TableColumn(0, 25);
        id_column.setHeaderValue("Id");
        columnModel.addColumn(id_column);

        TableColumn name_column = new TableColumn(1, 75);
        name_column.setHeaderValue("Person name");
        columnModel.addColumn(name_column);

        TableColumn title_column = new TableColumn(2, 75);
        title_column.setHeaderValue("DVD Title");
        columnModel.addColumn(title_column);

        TableColumn date_column = new TableColumn(3, 75);
        date_column.setHeaderValue("Borrow date");
        columnModel.addColumn(date_column);

        TableColumn state_column = new TableColumn(4, 75);
        state_column.setHeaderValue("State");
        columnModel.addColumn(state_column);

        loan_table.setAutoCreateColumnsFromModel(false);
        loan_table.setColumnModel(columnModel);

        load_loan_list();
    }

    private void load_loan_list() {
        sdf.applyPattern("yyyy.MM.dd.");

        Collection<Loan> loan_list = loanController.get();

        model.setRowCount(loan_list.size());

        int row_id = 0;
        for (Loan loan : loan_list) {
            model.setValueAt(loan.getId(), row_id, 0);
            model.setValueAt(loanController.getPerson(loan.getId()).getName(), row_id, 1);
            model.setValueAt(loanController.getDvd(loan.getId()).getTitle(), row_id, 2);
            model.setValueAt(sdf.format(loan.getBorrowDate()), row_id, 3);
            model.setValueAt(loan.getState().toString(), row_id, 4);
            model.setValueAt(loan.getCopyId(), row_id, 5);

            row_id++;
        }
    }

    private void filter_data() {
        sorter.setRowFilter(RowFilter.regexFilter(".*" + filter_field.getText() + ".*"));
    }

    public void handle_selection() {
        int selected_row = loan_table.getSelectedRow();

        if (selected_row < 0) {
            dVDDetailUI.clear_dvd();
            return;
        }

        long dvd_id = Long.valueOf(String.valueOf(model.getValueAt(selected_row, 0)));
        Loan loan = loanController.get(dvd_id);

        loanDetailUI.setLoan(loan);
        personDetailUI.setPerson(loanController.getPerson(loan.getId()));
        dVDDetailUI.setDvd(loanController.getDvd(loan.getId()));
    }

    @Override
    public void clear_selection() {
        loan_table.clearSelection();
        personDetailUI.clear_person();
    }

    @Override
    public void subselection_changed() {
    }

    @Override
    public void update_data() {
        load_loan_list();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        loan_context_menu = new javax.swing.JPopupMenu();
        extend_menu_item = new javax.swing.JMenuItem();
        return_menu_item = new javax.swing.JMenuItem();
        load_splitter = new javax.swing.JSplitPane();
        loan_detail_splitter = new javax.swing.JSplitPane();
        loan_loan_splitter = new javax.swing.JSplitPane();
        jPanel9 = new javax.swing.JPanel();
        jPanel10 = new javax.swing.JPanel();
        jPanel8 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane7 = new javax.swing.JScrollPane();
        loan_table = new javax.swing.JTable();
        filter_field = new javax.swing.JTextField();
        filter_label = new javax.swing.JLabel();

        loan_context_menu.setName("loan_context_menu"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(workshopdesign.WorkshopDesignApp.class).getContext().getActionMap(LoanUI.class, this);
        extend_menu_item.setAction(actionMap.get("extend_period")); // NOI18N
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(workshopdesign.WorkshopDesignApp.class).getContext().getResourceMap(LoanUI.class);
        extend_menu_item.setText(resourceMap.getString("extend_menu_item.text")); // NOI18N
        extend_menu_item.setName("extend_menu_item"); // NOI18N
        loan_context_menu.add(extend_menu_item);

        return_menu_item.setAction(actionMap.get("return_dvd")); // NOI18N
        return_menu_item.setText(resourceMap.getString("return_menu_item.text")); // NOI18N
        return_menu_item.setName("return_menu_item"); // NOI18N
        loan_context_menu.add(return_menu_item);

        setName("Form"); // NOI18N
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        load_splitter.setDividerLocation(550);
        load_splitter.setName("load_splitter"); // NOI18N

        loan_detail_splitter.setDividerLocation(150);
        loan_detail_splitter.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
        loan_detail_splitter.setName("loan_detail_splitter"); // NOI18N

        loan_loan_splitter.setDividerLocation(200);
        loan_loan_splitter.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
        loan_loan_splitter.setName("loan_loan_splitter"); // NOI18N

        jPanel9.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel9.border.title"))); // NOI18N
        jPanel9.setName("jPanel9"); // NOI18N

        javax.swing.GroupLayout jPanel9Layout = new javax.swing.GroupLayout(jPanel9);
        jPanel9.setLayout(jPanel9Layout);
        jPanel9Layout.setHorizontalGroup(
            jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 237, Short.MAX_VALUE)
        );
        jPanel9Layout.setVerticalGroup(
            jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 172, Short.MAX_VALUE)
        );

        loan_loan_splitter.setTopComponent(jPanel9);

        jPanel10.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel10.border.title"))); // NOI18N
        jPanel10.setName("jPanel10"); // NOI18N

        javax.swing.GroupLayout jPanel10Layout = new javax.swing.GroupLayout(jPanel10);
        jPanel10.setLayout(jPanel10Layout);
        jPanel10Layout.setHorizontalGroup(
            jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 237, Short.MAX_VALUE)
        );
        jPanel10Layout.setVerticalGroup(
            jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 245, Short.MAX_VALUE)
        );

        loan_loan_splitter.setRightComponent(jPanel10);

        loan_detail_splitter.setRightComponent(loan_loan_splitter);

        jPanel8.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel8.border.title"))); // NOI18N
        jPanel8.setName("jPanel8"); // NOI18N

        javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8);
        jPanel8.setLayout(jPanel8Layout);
        jPanel8Layout.setHorizontalGroup(
            jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 239, Short.MAX_VALUE)
        );
        jPanel8Layout.setVerticalGroup(
            jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 122, Short.MAX_VALUE)
        );

        loan_detail_splitter.setLeftComponent(jPanel8);

        load_splitter.setRightComponent(loan_detail_splitter);

        jPanel1.setName("jPanel1"); // NOI18N

        jScrollPane7.setName("jScrollPane7"); // NOI18N

        loan_table.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Id", "Person Name", "DVD Title", "Borrow Date", "State", "Copy ID"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Long.class, java.lang.String.class, java.lang.String.class, java.lang.Object.class, java.lang.Object.class, java.lang.Long.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        loan_table.setName("loan_table"); // NOI18N
        loan_table.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                loan_tableMousePressed(evt);
            }
        });
        jScrollPane7.setViewportView(loan_table);

        filter_field.setText(resourceMap.getString("filter_field.text")); // NOI18N
        filter_field.setName("filter_field"); // NOI18N

        filter_label.setText(resourceMap.getString("filter_label.text")); // NOI18N
        filter_label.setName("filter_label"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(filter_label)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(filter_field, javax.swing.GroupLayout.DEFAULT_SIZE, 517, Short.MAX_VALUE))
            .addComponent(jScrollPane7, javax.swing.GroupLayout.DEFAULT_SIZE, 549, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(filter_field, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(filter_label))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane7, javax.swing.GroupLayout.DEFAULT_SIZE, 608, Short.MAX_VALUE))
        );

        load_splitter.setLeftComponent(jPanel1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 809, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(0, 0, 0)
                    .addComponent(load_splitter, javax.swing.GroupLayout.DEFAULT_SIZE, 809, Short.MAX_VALUE)
                    .addGap(0, 0, 0)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 636, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(0, 0, 0)
                    .addComponent(load_splitter, javax.swing.GroupLayout.DEFAULT_SIZE, 636, Short.MAX_VALUE)
                    .addGap(0, 0, 0)))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        update_data();
        loanDetailUI.load_data();
    }//GEN-LAST:event_formComponentShown

    private void loan_tableMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_loan_tableMousePressed
        handle_selection();
    }//GEN-LAST:event_loan_tableMousePressed

    @Action
    public void return_dvd() {
        handle_selection();
        loanDetailUI.return_dvd();
        personDetailUI.load_data();
        dVDDetailUI.load_data();
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem extend_menu_item;
    private javax.swing.JTextField filter_field;
    private javax.swing.JLabel filter_label;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel10;
    private javax.swing.JPanel jPanel8;
    private javax.swing.JPanel jPanel9;
    private javax.swing.JScrollPane jScrollPane7;
    private javax.swing.JSplitPane load_splitter;
    private javax.swing.JPopupMenu loan_context_menu;
    private javax.swing.JSplitPane loan_detail_splitter;
    private javax.swing.JSplitPane loan_loan_splitter;
    private javax.swing.JTable loan_table;
    private javax.swing.JMenuItem return_menu_item;
    // End of variables declaration//GEN-END:variables
}
